import { Card, Space, Select, Form, Input, Button, Table, Image, message } from 'antd';
import { ToolOutlined } from '@ant-design/icons';
import { reqGetCityOrDistrictList, reqGetProvinceList, reqHospitalList, reqUpdateStatus } from '@/api/hospital/hospitalList';
import { useEffect, useState } from 'react';
import { IHospitalListData, IHospitalListParams, IResProvince } from '@/api/hospital/hospitalList/model/hospitalListType';
import { ColumnsType } from 'antd/lib/table';
import { useNavigate } from 'react-router-dom';
export default function HospitalList() {
  const navigate = useNavigate();

  const [hospitalList, setHospitalList] = useState<IHospitalListData[]>([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [province, setProvince] = useState<IResProvince[]>([]);
  const [city, setCity] = useState<IResProvince[]>([]);
  const [district, setDistrict] = useState<IResProvince[]>([]);
  const [hostype, setHostype] = useState<IResProvince[]>([]);
  const [form] = Form.useForm();
  useEffect(() => {
    getHospitalList();
    getProvince();
    getHosType();
  }, []);

  // 函数
  // 获取分页数据
  async function getHospitalList(page = 1, pageSize = 5, params?: IHospitalListParams) {
    setLoading(true);
    const res = await reqHospitalList(page, pageSize, params);
    setHospitalList(res.content);
    setTotal(res.totalElements);
    setLoading(false);
  }

  // 获取省数据
  async function getProvince() {
    const res = await reqGetProvinceList();
    setProvince(res);
  }

  // 获取市数据
  async function getCity(id: string) {
    const res = await reqGetCityOrDistrictList(id);
    setCity(res);
    // 把最后区数据给清空
    setDistrict([]);
  }

  // 获取区数据
  async function getDistrict(id: string) {
    const res = await reqGetCityOrDistrictList(id);
    setDistrict(res);
  }

  //获取医院类型
  async function getHosType() {
    const res = await reqGetCityOrDistrictList('10000');
    setHostype(res);
  }

  // 上线下线
  const updateStatus = async (id: string, status: 0 | 1) => {
    await reqUpdateStatus(id, status);
    message.success(`${status ? '上线成功' : '下线成功'}`);
    // 重新获取页面
    getHospitalList(page, pageSize);
  };

  // 查询
  const onFinish = async (values: IHospitalListParams) => {
    try {
      await getHospitalList(1, pageSize, values);
    } catch (error) {
      console.log(error);
      message.error('查询失败');
    }
  };

  // 清空
  const clear = async () => {
    // 清空所有选项
    form.resetFields();
    await getHospitalList(1, pageSize);
  };

  const columns: ColumnsType<IHospitalListData> = [
    {
      title: '序号',
      render(value, record, index) {
        return index + 1;
      },
      align: 'center',
      width: 80,
    },
    {
      title: '医院logo',
      dataIndex: 'logoData',
      render(value) {
        return <Image width={80} src={`data:image/jpeg;base64,${value}`} />;
      },
      align: 'center',
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      render(value, record, index) {
        return record.param.hostypeString;
      },
    },
    {
      title: '详细地址',
      render(value, record, index) {
        return record.param.fullAddress;
      },
    },
    {
      title: '状态',
      render(value, record, index) {
        return record.status == 0 ? '未上线' : '已上线';
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render(value, record, index) {
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                console.log(value);
                // 如果添加了parmas属性，则导航不会显示这个路由
                navigate(`/syt/hospital/hospitalList/show/${value.id}`, {
                  state: value,
                });
              }}>
              查看
            </Button>
            <Button
              type="primary"
              onClick={() => {
                navigate(`/syt/hospital/hospitalList/schedule/${record.hoscode}/${record.hosname}`);
              }}>
              排班
            </Button>
            <Button
              type="primary"
              danger={!!record.status}
              onClick={() => {
                updateStatus(record.id, record.status ? 0 : 1);
              }}>
              {record.status ? '下线' : '上线'}
            </Button>
          </Space>
        );
      },
    },
  ];

  return (
    <>
      <Card>
        <Form onFinish={onFinish} form={form} layout="inline" style={{ height: 104, alignContent: 'space-between' }}>
          <Form.Item style={{ width: 200 }} name="provinceCode">
            <Select
              placeholder="请选择省"
              onChange={async value => {
                // 选择的id
                // 选择省以后，发请求获取市的列表，清空后面两个的数据
                form.setFieldsValue({ cityCode: null, districtCode: null });
                console.log(value);
                getCity(value);
              }}
              options={province.map(item => ({
                label: item.name,
                value: item.value,
              }))}></Select>
          </Form.Item>

          <Form.Item style={{ width: 200 }} name="cityCode">
            <Select
              placeholder="请选择市"
              onChange={value => {
                // 选择的id
                // 选择市以后，发请求获取区的列表
                // 选择市区以后清空区的已选
                form.setFieldsValue({ districtCode: null });
                getDistrict(value);
              }}
              options={city.map(item => ({
                label: item.name,
                value: item.value,
              }))}></Select>
          </Form.Item>

          <Form.Item style={{ width: 200 }} name="districtCode">
            <Select
              placeholder="请选择区"
              options={district.map(item => ({
                label: item.name,
                value: item.value,
              }))}></Select>
          </Form.Item>

          <Form.Item style={{ width: 200 }} name="hosname">
            <Input placeholder="医院名称"></Input>
          </Form.Item>
          <Form.Item style={{ width: 200 }} name="hoscode">
            <Input placeholder="医院编号"></Input>
          </Form.Item>

          <Form.Item style={{ width: 200 }} name="hostype">
            <Select
              placeholder="医院类型"
              options={hostype.map(item => ({
                label: item.name,
                value: item.value,
              }))}></Select>
          </Form.Item>

          <Form.Item style={{ width: 200 }} name="status">
            <Select
              placeholder="医院状态"
              options={[
                { value: 1, label: '已上线' },
                { value: 0, label: '未上线' },
              ]}></Select>
          </Form.Item>

          <Form.Item>
            <Button htmlType="submit" type="primary" icon={<ToolOutlined />}>
              查询
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={clear}>清空</Button>
          </Form.Item>
        </Form>
        <Table
          loading={loading}
          bordered
          dataSource={hospitalList}
          columns={columns}
          style={{ marginTop: 20 }}
          rowKey={'id'}
          pagination={{
            total,
            pageSize,
            current: page,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: [3, 5, 10],
            showTotal(total, range) {
              return '居然有' + total + '页';
            },
            onChange(page, pageSize) {
              setPage(page);
              setPageSize(pageSize);
              getHospitalList(page, pageSize);
            },
          }}></Table>
      </Card>
    </>
  );
}
